<template>
  <div class="warehouse-container">
    <div class="filter-container">
      <el-input v-model="listQuery.agent_name" placeholder="门店名称" clearable class="filter-item input-item"
        style="width: 200px;" @clear="handleFilter" @keyup.enter.native="handleFilter" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit"
        @click="handleCreate">
        新增
      </el-button>
    </div>

    <div class="page-content">
      <el-table :key="tableKey" v-loading="listLoading" :data="list" border fit highlight-current-row
        style="width: 100%;">
        <el-table-column label="ID" prop="id" align="center" width="80" :class-name="getSortClass('id')">
          <template slot-scope="{row}">
            <span>{{ row.id_public_agent_info }}</span>
          </template>
        </el-table-column>
        <el-table-column label="门店名称" align="center">
          <template slot-scope="{row}">
            <span>{{ row.agent_name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="联系人" align="center">
          <template slot-scope="{row}">
            <span>{{ row.contact_name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="联系电话" align="center">
          <template slot-scope="{row}">
            <span>{{ row.agent_phone || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="门店地址" width="340" align="center">
          <template slot-scope="{row}">
            <span>{{ row.agent_province }} {{ row.agent_city }} {{ row.agent_country }} {{ row.agent_addr }}</span>
          </template>
        </el-table-column>
        <el-table-column label="注册时间" align="center">
          <template slot-scope="{row}">
            <span>{{ row.register_time || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="330" class-name="small-padding fixed-width">
          <template slot-scope="{row,$index}">
            <el-button type="primary" size="mini" @click="handleUpdate(row)">
              编辑
            </el-button>
            <el-button type="success" size="mini" @click="bindSupplier(row.id_public_agent_info)">
              绑定经纪人
            </el-button>
            <el-button type="warning" size="mini" @click="registerGoods(row.id_public_agent_info)">
              发布房屋
            </el-button>
            <el-button size="mini" type="danger" @click="handleDelete(row,$index)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <pagination v-show="total>0" :total="total" :page.sync="currentPage" :limit.sync="listQuery.limit"
        @pagination="getPageList" />

    <el-dialog :title="textMap[dialogStatus] + '门店'" :visible.sync="dialogFormVisible" :close-on-click-modal="false"
      width="45%">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="100px">
        <el-row :gutter="40">
          <el-col :span="12">
            <el-form-item label="门店名称" prop="agent_name">
              <el-input v-model="temp.agent_name" placeholder="请输入门店名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人" prop="contact_name">
              <el-input v-model="temp.contact_name" placeholder="请输入联系人名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="40">
          <el-col :span="12">
            <el-form-item label="联系电话" prop="agent_phone">
              <el-input v-model="temp.agent_phone" type="number" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所在省份" prop="agent_province">
              <el-select v-model="temp.agent_province" clearable :popper-append-to-body="false" placeholder="请选择省份"
                @change="selectProvince" @clear="clearData(1001)">
                <el-option v-for="item in provinceData" :key="item.value" :label="item.label" :value="item" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="40">
          <el-col :span="12">
            <el-form-item label="所在市" prop="agent_city">
              <el-select v-model="temp.agent_city" clearable :popper-append-to-body="false" placeholder="请选择市"
                @change="selectCity" @clear="clearData(1002)">
                <el-option v-for="item in citiesData" :key="item.value" :label="item.label" :value="item" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所在县(区)" prop="agent_country">
              <el-select v-model="temp.agent_country" clearable :popper-append-to-body="false" placeholder="请选择县(区)"
                @change="selectCityArea" @clear="clearData(1003)">
                <el-option v-for="item in cityAreaData" :key="item.value" :label="item.label" :value="item" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="40">
          <el-col>
            <el-form-item label="详细地址" prop="agent_addr" placeholder="请输入详细地址">
              <el-input v-model="temp.agent_addr" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { warehouseList } from '@/api/warehouse'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import areaData from '@/utils/area.json'

export default {
  name: 'SupplyManage',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    const validatePhone = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入手机号'))
      } else if (!(/^(13[0-9]|14[5-9]|15[0-3,5-9]|16[2,5,6,7]|17[0-8]|18[0-9]|19[0-3,5-9])\d{8}$/.test(value))) {
        this.temp.agent_phone = ''
        callback(new Error('手机号码格式不正确'))
      } else {
        callback()
      }
    }
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      currentPage: 0,
      listQuery: {
        invoke_method: 'public_page_4m_load_agent_list',
        pre_db_para_begin_idx: 0,
        pre_db_para_length_4_list: 10,
        agent_type_4_use: 20,
        pre_db_para_order_by_para: ' register_time desc ',
        agent_name: null,
        pre_db_para_is_online: 0
      },
      importanceOptions: [1, 2, 3],
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      temp: {
        id_public_agent_info: null,
        agent_name: null,
        contact_name: null,
        agent_phone: null,
        account_user: null,
        account_pwd: null,
        agent_province: null,
        agent_city: null,
        agent_country: null,
        agent_addr: null,
        is_online: 0,
        agent_type_4_user: 20
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        agent_name: [
          { required: true, message: '请输入供应商名称', trigger: 'blur' }
        ],
        contact_name: [
          { required: true, message: '请输入联系人名称', trigger: 'blur' }
        ],
        agent_phone: [
          { required: true, message: '请输入联系人电话', trigger: 'blur' },
          { validator: validatePhone, trigger: 'blur' }
        ],
        account_user: [
          { required: true, message: '请输入登录账户', trigger: 'blur' }
        ],
        agentPassword: [
          { required: true, message: '请输入登录密码', trigger: 'blur' }
        ],
        agent_province: [
          { required: true, message: '请选择所在省份', trigger: 'blur' }
        ],
        agent_city: [
          { required: true, message: '请选择所在市(区)', trigger: 'blur' }
        ],
        agent_country: [
          { required: true, message: '请选择所在县(区)', trigger: 'blur' }
        ],
        agent_addr: [
          { required: true, message: '请输入详细地址', trigger: 'blur' }
        ]
      },
      downloadLoading: false,
      /** 省份数据 */
      provinceData: [],
      provinceValue: '',
      /** 市数据 */
      citiesData: [],
      citiesValue: '',
      /** 区数据 */
      cityAreaData: [],
      cityAreaValue: ''
    }
  },
  created() {
    areaData.forEach(item => {
      this.provinceData.push({
        value: item.code,
        label: item.name,
        children: item.children
      })
    })
  },
  mounted() {
    this.getList()
  },
  methods: {
    /*
    * 获取页面数据
    * */
    getList() {
      this.listLoading = true
      warehouseList(this.Qs.stringify(this.listQuery)).then(response => {
        this.list = response.page_content
        this.total = response.result_num

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 0.5 * 1000)
      })
    },
    /*
    * 点击分页进行查询
    * */
    getPageList(val) {
      this.listQuery.pre_db_para_begin_idx = (val.page - 1) * this.listQuery.pre_db_para_length_4_list
      this.getList()
    },
    /*
    * 查询数据
    * */
    handleFilter() {
      this.listQuery.pre_db_para_begin_idx = 0
      this.getList()
    },
    resetTemp() {
      this.temp = {
        id_public_agent_info: null,
        agent_name: null,
        contact_name: null,
        agent_phone: null,
        account_user: null,
        account_pwd: null,
        agent_province: null,
        agent_city: null,
        agent_country: null,
        agent_addr: null,
        is_online: 0,
        agent_type_4_user: 20
      }
    },
    /*
    * 新增数据
    * */
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          console.log(this.temp)
          this.updateData()
          /*warehouseList(this.Qs.stringify({
            invoke_method: 'public_page_4m_insert_empty_agent',
            empower_code: 123,
            id_public_agent_info: this.list[0].id_public_agent_info,
            auto_inset_relation: true
          })).then(response => {
            this.temp.id_public_agent_info = response.page_content.id_public_agent_info
            this.updateData()
          })*/
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      const agentUpdateLoading = this.$loading({
        lock: true,
        text: '提交中，请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(255, 255, 255, .7)'
      });

      warehouseList(this.Qs.stringify({
        invoke_method: 'public_page_4m_insert_or_upd_agent_info',
        pre_db_para_id_public_agent_info: this.temp.id_public_agent_info,
        agent_name: this.temp.agent_name,
        contact_name: this.temp.contact_name,
        agent_phone: this.temp.agent_phone,
        account_user: this.temp.account_user,
        account_pwd: this.temp.account_pwd,
        agent_province: this.temp.agent_province,
        agent_city: this.temp.agent_city,
        agent_country: this.temp.agent_country,
        agent_addr: this.temp.agent_addr,
        is_online: 0,
        agent_type_4_use: 20
      })).then(response => {
        this.$notify({
          title: 'Success',
          message: '新增成功',
          type: 'success',
          duration: 2000
        })
        agentUpdateLoading&&agentUpdateLoading.close()
        this.dialogFormVisible = false
        if (this.dialogStatus === 'creat') {
          this.$notify({
            title: 'Success',
            message: '新增成功',
            type: 'success',
            duration: 2000
          })
        } else {
          this.$notify({
            title: 'Success',
            message: '编辑成功',
            type: 'success',
            duration: 2000
          })
        }
        this.getList()
      }).catch(() => {
        agentUpdateLoading&&agentUpdateLoading.close()
      })
    },
    handleDelete(row, index) {
      console.log(row)
      this.$confirm('您确定要删除该门店信息吗?', '提示', {
        type: 'warning'
      }).then(() => {
        warehouseList(this.Qs.stringify({
          invoke_method: 'public_page_4m_insert_or_upd_agent_info',
          pre_db_para_id_public_agent_info:row.id_public_agent_info,
          is_online: 111,
        })).then(() => {
          this.$notify({
            title: 'Success',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          if((this.total-1)==(this.currentPage-1)*this.listQuery.pre_db_para_length_4_list){
            if(this.currentPage-2>0||this.currentPage-2==0){
              this.listQuery.pre_db_para_begin_idx=(this.currentPage-2)*this.listQuery.pre_db_para_length_4_list
            }
          }
          this.getList()
        })
      }).catch(() => {
        this.getList()
      })
    },

    /*
    * 绑定供应商
    * */
    bindSupplier(id) {
      this.$router.push({ name: 'BindWarehouse', query: { agent_id: id }})
    },

    /*
    * 商品注册
    * */
    registerGoods(id) {
      this.$router.push({ name: 'RegisterGoods', query: { agent_id: id }})
    },

    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    },

    /** 选择所在省份 */
    selectProvince(val) {
      if (val) {
        this.citiesValue = val.children[0].name
        this.cityAreaValue = val.children[0].children[0].name
        this.temp.agent_province = val.label
        this.temp.agent_city = val.children[0].name
        this.temp.agent_country = val.children[0].children[0].name
        this.citiesData = []
        this.cityAreaData = []
        val.children.forEach(item => {
          this.citiesData.push({
            label: item.name,
            value: item.code,
            children: item.children
          })

          item.children.forEach(ele => {
            this.cityAreaData.push({
              label: ele.name,
              value: ele.code
            })
          })
        })
      }
    },
    /** 选择所在市 */
    selectCity(val) {
      if (val) {
        this.cityAreaValue = val.children[0].name
        this.temp.agent_city = val.label
        this.temp.agent_country = val.children[0].name
        this.cityAreaData = []
        val.children.forEach(item => {
          this.cityAreaData.push({
            label: item.name,
            value: item.code
          })
        })
      }
    },
    /** 选择所在区 */
    selectCityArea(val) {
      console.log(val)
      this.cityAreaValue = val.label
      this.temp.agent_country = val.label
    },
    /** 清空选择数据 */
    clearData(type) {
      switch (type) {
        case 1001:
          this.provinceValue = ''
          this.citiesValue = ''
          this.cityAreaValue = ''
          this.temp.agent_province = null
          this.temp.agent_city = null
          this.temp.agent_country = null
          break
        case 1002:
          this.citiesValue = ''
          this.cityAreaValue = ''
          this.temp.agent_city = null
          this.temp.agent_country = null
          break
        case 1003:
          this.cityAreaValue = ''
          this.temp.agent_country = null
          break
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.warehouse-container {
  margin: 24px 24px 0;
  padding: 16px;
  overflow: hidden;
  background-color: #fff;
  border-radius: 8px;

  .page-content {
    min-height: 500px;
  }

  .grid {
    position: relative;
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  }

  .input-item {
    margin-right: 24px;
  }
}
</style>
<style>
  .el-input__inner {
    line-height: 1px !important;
  }
  input[type="number"]::-webkit-inner-spin-button, input[type="number"]::-webkit-outer-spin-button {
    -webkit-appearance: none;
    margin: 0;
  }
</style>
